package download;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 * Create By IntelliJ IDEA
 *
 * @Author: jsonor
 * @Create-Time: 2017/9/30 8:59
 * @Description: 文件下载
 */
@WebServlet(name = "fileServlet", urlPatterns = "/file")
public class FileServlet extends HttpServlet {

  private static final Logger logger = Logger.getLogger(FileServlet.class);
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    ServletContext ctx = getServletContext();

    // 需要获取用户下载的文件名字
    String filename = req.getParameter("name");
    logger.info("file name : " + filename);

    // 获取对应的mime类型
    String mime = ctx.getMimeType(filename);

    // 设置响应头
    resp.setHeader("content-type", mime);
    resp.setHeader("Content-Disposition", "attachment; filename=" + filename);
    // 读取相应的文件，将其写入输出流中
    try {
      ServletOutputStream outputStream = resp.getOutputStream();
      InputStream inputStream = ctx.getClassLoader().getResourceAsStream("../files/" + filename);
      byte[] buffer = new byte[1024];
      while (inputStream.read(buffer) != -1) {
        outputStream.write(buffer);
      }
      inputStream.close();
    } catch (Exception ex) {
      logger.fatal(ex);
    }

    getPath();
  }

  private void getPath() {
    ServletContext ctx = getServletContext();

    try {
      logger.warn(ctx.getResource(""));
      logger.warn(ctx.getRealPath(""));
      logger.warn(ctx.getContextPath());
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }
}
